<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

	<meta name="baidu-site-verification" content="IwHYiEzBBM" />



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />










  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="android," />





  <link rel="alternate" href="/atom.xml" title="长孙雨聪--七星上将" type="application/atom+xml" />






<meta name="description" content="背景马上就到2018年过年了，然后我又刚好有兴致，就来玩玩Android中的简单几何图形的绘制和使用Path类来绘制路径。 Path和Canvas在Android中，和我们平时画图一样是有画笔和画布的，Path是画笔，Canvas是画布。与画的样式属性有关，如大小或者颜色等，是由Path来完成的；">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="Android中绘制简单几何图形和路径Path">
<meta property="og:url" content="http://zhangsunyucong.top/2018/02/06/android-simple-draw-and-path/index.html">
<meta property="og:site_name" content="长孙雨聪--七星上将">
<meta property="og:description" content="背景马上就到2018年过年了，然后我又刚好有兴致，就来玩玩Android中的简单几何图形的绘制和使用Path类来绘制路径。 Path和Canvas在Android中，和我们平时画图一样是有画笔和画布的，Path是画笔，Canvas是画布。与画的样式属性有关，如大小或者颜色等，是由Path来完成的；">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_17.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_1.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_02.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw__2.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_3.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_4.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_5.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_6.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_7.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_8.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_9.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_10.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_11.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_12.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_13.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_14.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_15.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_16.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_17.png">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_18.png">
<meta property="og:updated_time" content="2018-02-06T10:09:20.067Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android中绘制简单几何图形和路径Path">
<meta name="twitter:description" content="背景马上就到2018年过年了，然后我又刚好有兴致，就来玩玩Android中的简单几何图形的绘制和使用Path类来绘制路径。 Path和Canvas在Android中，和我们平时画图一样是有画笔和画布的，Path是画笔，Canvas是画布。与画的样式属性有关，如大小或者颜色等，是由Path来完成的；">
<meta name="twitter:image" content="http://o8bym0zmt.bkt.clouddn.com/android_draw_17.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://zhangsunyucong.top/2018/02/06/android-simple-draw-and-path/"/>





  <title>Android中绘制简单几何图形和路径Path | 长孙雨聪--七星上将</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
	
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">长孙雨聪--七星上将</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">坚持不懈，必有回响。</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-github">
          <a href="https://github.com/zhangsunyucong?tab=repositories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            Github
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
  
     

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhangsunyucong.top/2018/02/06/android-simple-draw-and-path/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="长孙雨聪--七星上将">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/myphoto.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="长孙雨聪--七星上将">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Android中绘制简单几何图形和路径Path</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-02-06T13:56:29+08:00">
                2018-02-06
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-02-06T18:09:20+08:00">
                2018-02-06
              </time>
            
          </span>

          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2018/02/06/android-simple-draw-and-path/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2018/02/06/android-simple-draw-and-path/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2018/02/06/android-simple-draw-and-path/" class="leancloud_visitors" data-flag-title="Android中绘制简单几何图形和路径Path">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,952字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  15分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><hr>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_17.png" alt="图片"></p>
<h3 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h3><p>马上就到2018年过年了，然后我又刚好有兴致，就来玩玩Android中的简单几何图形的绘制和使用Path类来绘制路径。</p>
<h3 id="Path和Canvas"><a href="#Path和Canvas" class="headerlink" title="Path和Canvas"></a>Path和Canvas</h3><p>在Android中，和我们平时画图一样是有画笔和画布的，Path是画笔，Canvas是画布。与画的样式属性有关，如大小或者颜色等，是由Path来完成的；<a id="more"></a>与画的形状，即画什么东西是由Canva完成的。关于这两个类的各个属性和方法的具体使用，可以浏览<a href="http://blog.csdn.net/aigestudio/article/details/41316141" target="_blank" rel="noopener">爱哥的博客</a>几篇文章。在这里，只是用它们简单的几个函数画一些简单的图形，最后还会给出一个综合一点的demo,主要是为了加强认识绘制时坐标关系。</p>
<p>先贴上我的代码：<br>布局文件：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span><br><span class="line">&lt;LinearLayout</span><br><span class="line">    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</span><br><span class="line">    android:orientation=&quot;vertical&quot;</span><br><span class="line">    android:id=&quot;@+id/root_draw_view&quot;</span><br><span class="line">    android:gravity=&quot;center_horizontal&quot;</span><br><span class="line">    android:layout_width=&quot;match_parent&quot;</span><br><span class="line">    android:layout_height=&quot;match_parent&quot;&gt;</span><br><span class="line"></span><br><span class="line">    &lt;TextView</span><br><span class="line">        android:layout_width=&quot;match_parent&quot;</span><br><span class="line">        android:layout_height=&quot;wrap_content&quot;</span><br><span class="line">        android:gravity=&quot;center&quot;</span><br><span class="line">        android:text=&quot;有点意思&quot;/&gt;</span><br><span class="line"></span><br><span class="line">    &lt;com.example.hyj.ht_test.widget.draw.MyDrawView</span><br><span class="line">        android:layout_width=&quot;300dp&quot;</span><br><span class="line">        android:layout_height=&quot;300dp&quot; /&gt;</span><br><span class="line"></span><br><span class="line">&lt;/LinearLayout&gt;</span><br></pre></td></tr></table></figure></p>
<p>MyDrawView.java<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line">public class MyDrawView extends View &#123;</span><br><span class="line"></span><br><span class="line">    private Paint mPointPaint;</span><br><span class="line">    private float[] mFPts;</span><br><span class="line">    private RectF mRectF;</span><br><span class="line">    private RectF mRectOvalF;</span><br><span class="line">    private RectF mRightBottomRectF;</span><br><span class="line">    private Path mPath;</span><br><span class="line">    private Path mPath1;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context) &#123;</span><br><span class="line">        super(context);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context, @Nullable AttributeSet attrs) &#123;</span><br><span class="line">        super(context, attrs);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) &#123;</span><br><span class="line">        super(context, attrs, defStyleAttr);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private int mPointStrokeWidth;</span><br><span class="line"></span><br><span class="line">    private void init() &#123;</span><br><span class="line">        mPointStrokeWidth = 20;</span><br><span class="line">        mPointPaint = new Paint();</span><br><span class="line">        mPointPaint.setColor(Color.RED);</span><br><span class="line">        mPointPaint.setStrokeWidth(mPointStrokeWidth);</span><br><span class="line">        mPointPaint.setStyle(Paint.Style.FILL);</span><br><span class="line"></span><br><span class="line">        mPath = new Path();</span><br><span class="line">        mPath1 = new Path();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) &#123;</span><br><span class="line">        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);</span><br><span class="line">        int widthMode = MeasureSpec.getMode(widthMeasureSpec);</span><br><span class="line">        int widthSize = MeasureSpec.getSize(widthMeasureSpec);</span><br><span class="line"></span><br><span class="line">        int heightMode = MeasureSpec.getMode(heightMeasureSpec);</span><br><span class="line">        int heightSize = MeasureSpec.getSize(heightMeasureSpec);</span><br><span class="line"></span><br><span class="line">        int widthResult = 100;</span><br><span class="line">        int heightResult = 100;</span><br><span class="line"></span><br><span class="line">        if(widthMode != MeasureSpec.AT_MOST) &#123;</span><br><span class="line">            widthResult = widthSize;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if(heightMode != MeasureSpec.AT_MOST) &#123;</span><br><span class="line">            heightResult = heightSize;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        int resultSize = widthResult &gt; heightResult</span><br><span class="line">                ? heightResult : widthResult;</span><br><span class="line"></span><br><span class="line">        setMeasuredDimension(resultSize, resultSize);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onSizeChanged(int w, int h, int oldw, int oldh) &#123;</span><br><span class="line">        super.onSizeChanged(w, h, oldw, oldh);</span><br><span class="line">        mFPts = new float[] &#123;</span><br><span class="line">                0, 0,</span><br><span class="line">                getMeasuredWidth() / 2, 0,</span><br><span class="line">                getMeasuredWidth(), 0,</span><br><span class="line">                getMeasuredWidth(), getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredWidth(), getMeasuredHeight(),</span><br><span class="line">                getMeasuredWidth() / 2, getMeasuredHeight(),</span><br><span class="line">                0, getMeasuredHeight(),</span><br><span class="line">                0, getMeasuredHeight() /2,</span><br><span class="line">                getMeasuredHeight() / 2, getMeasuredHeight() /2</span><br><span class="line">        &#125;;</span><br><span class="line">        mRectF = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());</span><br><span class="line">        mRectOvalF = new RectF(mPointStrokeWidth, mPointStrokeWidth,</span><br><span class="line">                getMeasuredWidth() - mPointStrokeWidth, getMeasuredHeight() / 2);</span><br><span class="line">        mRightBottomRectF = new RectF(getMeasuredWidth() / 2, getMeasuredHeight() /2,</span><br><span class="line">                getMeasuredWidth() - mPointStrokeWidth, getMeasuredHeight() - mPointStrokeWidth);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onDraw(Canvas canvas) &#123;</span><br><span class="line">        super.onDraw(canvas);</span><br><span class="line"></span><br><span class="line">        canvas.drawLine(mFPts[0], mFPts[1], mFPts[2], mFPts[2], mPointPaint);</span><br><span class="line">        mPointPaint.setColor(Color.BLUE);</span><br><span class="line">        canvas.drawLines(mFPts, mPointPaint);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>MyDrawView中没有考虑padding的影响。</p>
<h4 id="画点"><a href="#画点" class="headerlink" title="画点"></a>画点</h4><p>几何图形中，最简单的就是点了，首先画点。</p>
<blockquote>
<p>drawPoint(float x, float y, Paint paint)<br>drawPoints(float[] pts, Paint paint)<br>drawPoints(float[] pts, int offset, int count, Paint paint)</p>
</blockquote>
<p>x是点的横坐标，y是点的纵坐标。坐标的点也可以放到数组pts中，可见数组的个数一般是偶数个，offset是开始绘制前，数组中忽略的元素个数。count是忽略了offset个点后，开始取count个元素来绘制点。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">canvas.drawPoints(mFPts, mPointPaint);</span><br><span class="line">mPointPaint.setColor(Color.BLUE);</span><br><span class="line">canvas.drawPoint(getMeasuredWidth() / 2, 0, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_1.png" alt="图片"></p>
<h4 id="画线"><a href="#画线" class="headerlink" title="画线"></a>画线</h4><p>由点组成线，两点确定一条直线。</p>
<blockquote>
<p>drawLine(float startX, float startY, float stopX, float stopY, Paint paint)<br>drawLines(float[] pts, int offset, int count, Paint paint)<br>drawLines(float[] pts, Paint paint)</p>
</blockquote>
<p>第一个是，直接指定直线的两个点坐标。pts是点的坐标，每两个数组元素确定一个点坐标，每四个元素确定直线的两个点的坐标。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">canvas.drawLine(mFPts[0], mFPts[1], mFPts[2], mFPts[2], mPointPaint);</span><br><span class="line">mPointPaint.setColor(Color.BLUE);</span><br><span class="line">canvas.drawLines(mFPts, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_02.png" alt="图片"></p>
<h4 id="画矩形"><a href="#画矩形" class="headerlink" title="画矩形"></a>画矩形</h4><p>由线可以组成面。矩形可以是长方形，也可以是正方形。</p>
<p>RectF和Rect的区别是参数的类型不同，RectF的参数类型是float，Rect的参数类型是int。</p>
<blockquote>
<p>drawRect(float left, float top, float right, float bottom, Paint paint)<br>drawRect(float left, float top, float right, float bottom, Paint paint)<br>drawRect(Rect r, Paint paint)<br>drawRect( RectF rect, Paint paint)</p>
</blockquote>
<p>也就是，可以在RectF或者Rect中指定好顶点坐标再传给drawRect，也可以在drawRect方法中直接指定顶点坐标。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mRectF = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());</span><br><span class="line">canvas.drawRect(mRectF, mPointPaint);</span><br></pre></td></tr></table></figure>
<p>代码说明，第一行代码是在onSizeChanged重写方法中的，第二行代码是在onDraw方法中的。因为onDraw方法是会不断被调用的，不适合在里面创建对象。</p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw__2.png" alt="图片"></p>
<h4 id="圆角矩形"><a href="#圆角矩形" class="headerlink" title="圆角矩形"></a>圆角矩形</h4><p>圆角矩形是在矩形的基础上生成的。</p>
<blockquote>
<p>drawRoundRect(RectF rect, float rx, float ry, Paint paint)<br>drawRoundRect(float left, float top, float right, float bottom, float rx, float ry, Paint paint)</p>
</blockquote>
<p>rx是生成圆角的椭圆的X轴半径<br>ry是生成圆角的椭圆的Y轴半径</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">canvas.drawRoundRect(mRectF, getMeasuredWidth() / 4, getMeasuredHeight() / 4, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_3.png" alt="图片"></p>
<h4 id="画圆"><a href="#画圆" class="headerlink" title="画圆"></a>画圆</h4><p>圆要指定圆心的坐标和半径的大小。</p>
<blockquote>
<p>drawCircle(float cx, float cy, float radius, Paint paint)</p>
</blockquote>
<p>cx和cy分别是圆心的横坐标和纵坐标，radius为半径。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredHeight() / 2 - mPointStrokeWidth, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_4.png" alt="图片"></p>
<h4 id="画椭圆"><a href="#画椭圆" class="headerlink" title="画椭圆"></a>画椭圆</h4><p>椭圆是在矩形基础上生成的，以矩形的长为长轴，矩形的宽为短轴。特殊的，当长轴等于短轴时，椭圆就是圆。</p>
<blockquote>
<p>drawOval(RectF oval, @NonNull Paint paint)<br>drawOval(float left, float top, float right, float bottom, Paint paint)</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mRectOvalF = new RectF(mPointStrokeWidth, mPointStrokeWidth,</span><br><span class="line">                getMeasuredWidth() - mPointStrokeWidth, getMeasuredHeight() / 2);</span><br><span class="line">                </span><br><span class="line">canvas.drawOval(mRectOvalF, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_5.png" alt="图片"></p>
<h4 id="画弧"><a href="#画弧" class="headerlink" title="画弧"></a>画弧</h4><p>弧是在椭圆上按一定角度截取的一部分。</p>
<blockquote>
<p>drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)<br>drawArc(float left, float top, float right, float bottom, float startAngle,<br>            float sweepAngle, boolean useCenter, Paint paint)</p>
</blockquote>
<p>oval是椭圆基于的矩形顶点的矩阵，或者在方法中直接指定四个顶点，startAngle是截取的起始角度，sweepAngle是弧持续的角度，useCenter是否显示长短半径。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">canvas.drawArc(mRectOvalF, 0, 90, true, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_6.png" alt="图片"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">canvas.drawArc(mRectOvalF, 0, 90, false, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_7.png" alt="图片"></p>
<h3 id="Path"><a href="#Path" class="headerlink" title="Path"></a>Path</h3><p>在View的绘制过程中，有一个类叫做Path，Path可以帮助我们实现很多自定义形状的路径，特别是配合xfermode属性来使用的时候，可以实现很多效果。</p>
<h4 id="moveTo"><a href="#moveTo" class="headerlink" title="moveTo"></a>moveTo</h4><p>路径开始绘制的点叫起始点坐标，默认是（0，0）。可以使用moveTo将绘制路径的起始点移动到某个位置。moveTo不进行绘制，一般用来移动画笔。</p>
<h4 id="lineTo"><a href="#lineTo" class="headerlink" title="lineTo"></a>lineTo</h4><p>lineTo用来绘制一条直线路径。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mPath.moveTo(getMeasuredWidth()/ 2, getMeasuredHeight() / 2);</span><br><span class="line">mPath.lineTo(getMeasuredWidth(), getMeasuredHeight());</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p>直线路径的起始点是(getMeasuredWidth()/ 2, getMeasuredHeight() / 2)，终点是(getMeasuredWidth(), getMeasuredHeight())</p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_8.png" alt="图片"></p>
<h4 id="quadTo"><a href="#quadTo" class="headerlink" title="quadTo"></a>quadTo</h4><p>quadTo用来画由一个控制点控制的贝塞尔曲线。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mPath.moveTo(mPointStrokeWidth, getMeasuredHeight() / 2);</span><br><span class="line">mPath.quadTo(0, 0, getMeasuredWidth() / 2, mPointStrokeWidth);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p>起始点是(mPointStrokeWidth, getMeasuredHeight() / 2)，控制点是（0， 0），终点是（getMeasuredWidth() / 2, mPointStrokeWidth）</p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_9.png" alt="图片"></p>
<h4 id="cubicTo"><a href="#cubicTo" class="headerlink" title="cubicTo"></a>cubicTo</h4><p>cubicTo用来画由两个控制点控制的贝塞尔曲线。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mPath.moveTo(mPointStrokeWidth, getMeasuredHeight() / 2);</span><br><span class="line">mPath.cubicTo(0, 0, getMeasuredWidth() / 2, mPointStrokeWidth,</span><br><span class="line">         getMeasuredWidth(), getMeasuredHeight() / 2);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p>起始点是(mPointStrokeWidth, getMeasuredHeight() / 2)，两个控制点是（0， 0）和（getMeasuredWidth() / 2, mPointStrokeWidth），终点是（getMeasuredWidth(), getMeasuredHeight() / 2）。</p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_10.png" alt="图片"></p>
<h4 id="arcTo"><a href="#arcTo" class="headerlink" title="arcTo"></a>arcTo</h4><p>arcTo用来画一条圆弧路径。与前面画圆弧一样的，圆弧是截取椭圆的一部分，而椭圆是基于矩形的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mRectOvalF = new RectF(mPointStrokeWidth, mPointStrokeWidth,</span><br><span class="line">    getMeasuredWidth() - mPointStrokeWidth, getMeasuredHeight() / 2);</span><br><span class="line">mPath.arcTo(mRectOvalF, 0, 90, false);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p>和刚开始的圆弧参数定义一样，指定基于的矩形的四个顶点，startAngle截取的起始角度，sweepAngle弧持续的角度，useCenter是否显示长短半径。</p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_11.png" alt="图片"></p>
<h3 id="Path的addArc、addRoundRect、addOval、addRect、addCircle"><a href="#Path的addArc、addRoundRect、addOval、addRect、addCircle" class="headerlink" title="Path的addArc、addRoundRect、addOval、addRect、addCircle"></a>Path的addArc、addRoundRect、addOval、addRect、addCircle</h3><p>它们实现的几何路径,可以自己尝试一下。</p>
<h3 id="Path-Op"><a href="#Path-Op" class="headerlink" title="Path.Op"></a>Path.Op</h3><p>在开头，mPointPaint首先设置画笔的样式为描边STROKE，后面为了更好看出Path.Op的效果会改为FILL填充。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mRightBottomRectF = new RectF(getMeasuredWidth() / 2, getMeasuredHeight() /2, getMeasuredWidth() - mPointStrokeWidth, getMeasuredHeight() - mPointStrokeWidth);</span><br><span class="line"></span><br><span class="line">mPath.addCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2,</span><br><span class="line">    getMeasuredHeight() / 2 - mPointStrokeWidth, Path.Direction.CCW);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br><span class="line">mPath1.addRect(mRightBottomRectF, Path.Direction.CCW);</span><br><span class="line">canvas.drawPath(mPath1, mPointPaint);</span><br></pre></td></tr></table></figure></p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_12.png" alt="图片"></p>
<h4 id="Path-Op-DIFFERENCE"><a href="#Path-Op-DIFFERENCE" class="headerlink" title="Path.Op.DIFFERENCE"></a>Path.Op.DIFFERENCE</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mPath.addCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredHeight() / 2 - mPointStrokeWidth,</span><br><span class="line">                Path.Direction.CCW);</span><br><span class="line">mPath1.addRect(mRightBottomRectF, Path.Direction.CCW);</span><br><span class="line">mPath.op(mPath1, Path.Op.DIFFERENCE);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_13.png" alt="图片"></p>
<h4 id="Path-Op-INTERSECT"><a href="#Path-Op-INTERSECT" class="headerlink" title="Path.Op.INTERSECT"></a>Path.Op.INTERSECT</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mPath.addCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredHeight() / 2 - mPointStrokeWidth,</span><br><span class="line">                Path.Direction.CCW);</span><br><span class="line">mPath1.addRect(mRightBottomRectF, Path.Direction.CCW);</span><br><span class="line">mPath.op(mPath1, Path.Op.INTERSECT);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_14.png" alt="图片"></p>
<h4 id="Path-Op-REVERSE-DIFFERENCE"><a href="#Path-Op-REVERSE-DIFFERENCE" class="headerlink" title="Path.Op.REVERSE_DIFFERENCE"></a>Path.Op.REVERSE_DIFFERENCE</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mPath.addCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredHeight() / 2 - mPointStrokeWidth,</span><br><span class="line">                Path.Direction.CCW);</span><br><span class="line">mPath1.addRect(mRightBottomRectF, Path.Direction.CCW);</span><br><span class="line">mPath.op(mPath1, Path.Op.REVERSE_DIFFERENCE);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_15.png" alt="图片"></p>
<h4 id="Path-Op-XOR"><a href="#Path-Op-XOR" class="headerlink" title="Path.Op.XOR"></a>Path.Op.XOR</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mPath.addCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredHeight() / 2 - mPointStrokeWidth,</span><br><span class="line">                Path.Direction.CCW);</span><br><span class="line">mPath1.addRect(mRightBottomRectF, Path.Direction.CCW);</span><br><span class="line">mPath.op(mPath1, Path.Op.XOR);</span><br><span class="line">canvas.drawPath(mPath, mPointPaint);</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_16.png" alt="图片"></p>
<h3 id="最后，例子"><a href="#最后，例子" class="headerlink" title="最后，例子"></a>最后，例子</h3><p>（一）例子一<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br></pre></td><td class="code"><pre><span class="line">public class MyDrawView extends View &#123;</span><br><span class="line"></span><br><span class="line">    private Paint mGraphPaint;</span><br><span class="line">    private Paint mPointPaint;</span><br><span class="line">    private Paint mRectPaint;</span><br><span class="line">    private RectF mRectF;</span><br><span class="line">    private Paint mLinesPaint;</span><br><span class="line">    private float mFPts[];</span><br><span class="line">    private float mFLinePts[];</span><br><span class="line">    private Path mPath;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context) &#123;</span><br><span class="line">        super(context);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context, @Nullable AttributeSet attrs) &#123;</span><br><span class="line">        super(context, attrs);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) &#123;</span><br><span class="line">        super(context, attrs, defStyleAttr);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private int mPointStrokeWidth;</span><br><span class="line"></span><br><span class="line">    private void init() &#123;</span><br><span class="line">        mGraphPaint = new Paint();</span><br><span class="line">        mGraphPaint.setColor(Color.GREEN);</span><br><span class="line">        mGraphPaint.setStrokeWidth(5);</span><br><span class="line">        mGraphPaint.setStyle(Paint.Style.STROKE);</span><br><span class="line">        mGraphPaint.setShadowLayer(50, 30,30, Color.BLUE);</span><br><span class="line"></span><br><span class="line">        mPointStrokeWidth = 20;</span><br><span class="line">        mPointPaint = new Paint();</span><br><span class="line">        mPointPaint.setColor(Color.RED);</span><br><span class="line">        mPointPaint.setStrokeWidth(mPointStrokeWidth);</span><br><span class="line">        mPointPaint.setStyle(Paint.Style.FILL);</span><br><span class="line"></span><br><span class="line">        mRectPaint = new Paint();</span><br><span class="line">        mRectPaint.setColor(Color.BLACK);</span><br><span class="line">        mRectPaint.setStrokeWidth(5);</span><br><span class="line">        mRectPaint.setStyle(Paint.Style.STROKE);</span><br><span class="line"></span><br><span class="line">        mLinesPaint = new Paint();</span><br><span class="line">        mLinesPaint.setColor(Color.GRAY);</span><br><span class="line">        mLinesPaint.setStrokeWidth(5);</span><br><span class="line">        mLinesPaint.setStyle(Paint.Style.STROKE);</span><br><span class="line"></span><br><span class="line">        mPath = new Path();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) &#123;</span><br><span class="line">        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);</span><br><span class="line">        int widthMode = MeasureSpec.getMode(widthMeasureSpec);</span><br><span class="line">        int widthSize = MeasureSpec.getSize(widthMeasureSpec);</span><br><span class="line"></span><br><span class="line">        int heightMode = MeasureSpec.getMode(heightMeasureSpec);</span><br><span class="line">        int heightSize = MeasureSpec.getSize(heightMeasureSpec);</span><br><span class="line"></span><br><span class="line">        int widthResult = 100;</span><br><span class="line">        int heightResult = 100;</span><br><span class="line"></span><br><span class="line">        if(widthMode != MeasureSpec.AT_MOST) &#123;</span><br><span class="line">            widthResult = widthSize;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if(heightMode != MeasureSpec.AT_MOST) &#123;</span><br><span class="line">            heightResult = heightSize;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        int resultSize = widthResult &gt; heightResult</span><br><span class="line">                ? heightResult : widthResult;</span><br><span class="line"></span><br><span class="line">        setMeasuredDimension(resultSize, resultSize);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private int num = 30;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onSizeChanged(int w, int h, int oldw, int oldh) &#123;</span><br><span class="line">        super.onSizeChanged(w, h, oldw, oldh);</span><br><span class="line">        mRectF = new RectF(</span><br><span class="line">                num - mPointStrokeWidth / 2,</span><br><span class="line">                num - mPointStrokeWidth / 2,</span><br><span class="line">                getMeasuredWidth() - num +  mPointStrokeWidth / 2,</span><br><span class="line">                getMeasuredHeight() - num + mPointStrokeWidth / 2);</span><br><span class="line"></span><br><span class="line">        mFPts = new float[] &#123;</span><br><span class="line">                getMeasuredWidth() / 2, num,</span><br><span class="line">                getMeasuredWidth() - num, getMeasuredHeight()/ 2,</span><br><span class="line">                getMeasuredWidth() / 2 ,getMeasuredHeight() - num,</span><br><span class="line">                num, getMeasuredHeight()/ 2</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onDraw(Canvas canvas) &#123;</span><br><span class="line">        super.onDraw(canvas);</span><br><span class="line"></span><br><span class="line">        canvas.drawCircle( getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredHeight() / 2,</span><br><span class="line">                getMeasuredHeight() / 2 - num,</span><br><span class="line">                mGraphPaint);</span><br><span class="line"></span><br><span class="line">        canvas.drawRect(mRectF, mRectPaint);</span><br><span class="line"></span><br><span class="line">        canvas.drawPoints(mFPts, mPointPaint);</span><br><span class="line"></span><br><span class="line">        canvas.drawLines(mFPts, mLinesPaint);</span><br><span class="line"></span><br><span class="line">        mPath.moveTo(mFPts[0], mFPts[1]);</span><br><span class="line">        mPath.lineTo(mFPts[2], mFPts[3]);</span><br><span class="line">        mPath.lineTo(mFPts[4], mFPts[5]);</span><br><span class="line">        mPath.lineTo(mFPts[6], mFPts[7]);</span><br><span class="line">        mPath.close();</span><br><span class="line">        canvas.drawPath(mPath, mLinesPaint);</span><br><span class="line"></span><br><span class="line">        canvas.drawLine(mFPts[0], mFPts[1], mFPts[4], mFPts[5], mLinesPaint);</span><br><span class="line">        canvas.drawLine(mFPts[2], mFPts[3], mFPts[6], mFPts[7], mLinesPaint);</span><br><span class="line"></span><br><span class="line">        mPath.moveTo(mFPts[6], mFPts[7]);</span><br><span class="line">        mPath.quadTo(mFPts[0], mFPts[1], mFPts[2], mFPts[3]);</span><br><span class="line">        canvas.drawPath(mPath, mLinesPaint);</span><br><span class="line"></span><br><span class="line">        mPath.moveTo(num - mPointStrokeWidth / 2,</span><br><span class="line">                getMeasuredHeight() - num + mPointStrokeWidth / 2);</span><br><span class="line">        mPath.cubicTo(mFPts[4], mFPts[5],</span><br><span class="line">                getMeasuredWidth() - num +  mPointStrokeWidth / 2, getMeasuredHeight() - num +</span><br><span class="line">                        mPointStrokeWidth / 2,</span><br><span class="line">                mFPts[2], mFPts[3]);</span><br><span class="line">        canvas.drawPath(mPath, mLinesPaint);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>效果图：</p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_17.png" alt="图片"></p>
<p>（二）例子二</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line">public class MyDrawView extends View &#123;</span><br><span class="line"></span><br><span class="line">    private Paint mPaint;</span><br><span class="line"></span><br><span class="line">    private int mOffsetX;</span><br><span class="line">    private int mOffsetY;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context) &#123;</span><br><span class="line">        super(context);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context, @Nullable AttributeSet attrs) &#123;</span><br><span class="line">        super(context, attrs);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public MyDrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) &#123;</span><br><span class="line">        super(context, attrs, defStyleAttr);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    private void init() &#123;</span><br><span class="line">        mPaint = new Paint();</span><br><span class="line">        mPaint.setColor(Color.RED);</span><br><span class="line">        mPaint.setStrokeWidth(5);</span><br><span class="line">        mPaint.setStyle(Paint.Style.STROKE);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) &#123;</span><br><span class="line">        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);</span><br><span class="line">        int widthMode = MeasureSpec.getMode(widthMeasureSpec);</span><br><span class="line">        int widthSize = MeasureSpec.getSize(widthMeasureSpec);</span><br><span class="line"></span><br><span class="line">        int heightMode = MeasureSpec.getMode(heightMeasureSpec);</span><br><span class="line">        int heightSize = MeasureSpec.getSize(heightMeasureSpec);</span><br><span class="line"></span><br><span class="line">        int widthResult = 100;</span><br><span class="line">        int heightResult = 100;</span><br><span class="line"></span><br><span class="line">        if(widthMode != MeasureSpec.AT_MOST) &#123;</span><br><span class="line">            widthResult = widthSize;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if(heightMode != MeasureSpec.AT_MOST) &#123;</span><br><span class="line">            heightResult = heightSize;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        int resultSize = widthResult &gt; heightResult</span><br><span class="line">                ? heightResult : widthResult;</span><br><span class="line"></span><br><span class="line">        setMeasuredDimension(resultSize, resultSize);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onSizeChanged(int w, int h, int oldw, int oldh) &#123;</span><br><span class="line">        super.onSizeChanged(w, h, oldw, oldh);</span><br><span class="line">        mOffsetX = w / 2;</span><br><span class="line">        mOffsetY = h / 2 - 55;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private Point getHeartPoint(float angle) &#123;</span><br><span class="line">        float t = (float) (angle / Math.PI);</span><br><span class="line">        float x = (float) (19.5 * (16 * Math.pow(Math.sin(t), 3)));</span><br><span class="line">        float y = (float) (-20 * (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)));</span><br><span class="line">        return new Point(mOffsetX + (int) x, mOffsetY + (int) y);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onDraw(Canvas canvas) &#123;</span><br><span class="line">        super.onDraw(canvas);</span><br><span class="line"></span><br><span class="line">        float angle = 10;</span><br><span class="line">        while (angle &lt; 180) &#123;</span><br><span class="line">            Point p = getHeartPoint(angle);</span><br><span class="line">            canvas.drawPoint(p.x, p.y, mPaint);</span><br><span class="line">            angle = angle + 0.02f;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android_draw_18.png" alt="图片"></p>
<p>关于画笔和画布的使用，到这里是未完的，其他的效果，以后有时间再补充。谢谢大家的观看。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
	  
		<!--MOB SHARE BEGIN-->
 <button id="rewardButton" class="-mob-share-open" style="margin-right:5px;">
    <span>分享</span>
  </button>
<div class="-mob-share-ui" style="display: none">
    <ul class="-mob-share-list">
        <li class="-mob-share-weibo"><p>新浪微博</p></li>
            <li class="-mob-share-tencentweibo"><p>腾讯微博</p></li>
            <li class="-mob-share-qzone"><p>QQ空间</p></li>
            <li class="-mob-share-qq"><p>QQ好友</p></li>
            <li class="-mob-share-weixin"><p>微信</p></li>
            <li class="-mob-share-douban"><p>豆瓣</p></li>
            <li class="-mob-share-renren"><p>人人网</p></li>
            <li class="-mob-share-kaixin"><p>开心网</p></li>
            <li class="-mob-share-facebook"><p>Facebook</p></li>
            <li class="-mob-share-twitter"><p>Twitter</p></li>
            <li class="-mob-share-pocket"><p>Pocket</p></li>
            <li class="-mob-share-google"><p>Google+</p></li>
            <li class="-mob-share-youdao"><p>有道云笔记</p></li>
    </ul>
    <div class="-mob-share-close">取消</div>
</div>
<div class="-mob-share-ui-bg"></div>
<script id="-mob-share" src="https://f1.webshare.mob.com/code/mob-share.js?appkey=230df6a994c78"></script>
<!--MOB SHARE END-->
      
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  
  
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="长孙雨聪--七星上将 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="长孙雨聪--七星上将 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
	  
	</div>

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    长孙雨聪--七星上将
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://zhangsunyucong.top/2018/02/06/android-simple-draw-and-path/" title="Android中绘制简单几何图形和路径Path">http://zhangsunyucong.top/2018/02/06/android-simple-draw-and-path/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/android/" rel="tag"><i class="fa fa-tag"></i> android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/02/node-async-promise/" rel="next" title="初始Promise/A+规范">
                <i class="fa fa-chevron-left"></i> 初始Promise/A+规范
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/02/07/android-animation-matrix/" rel="prev" title="从矩阵来看Android中的一些动画变换">
                从矩阵来看Android中的一些动画变换 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>

  
	  
	  
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
			<a href="/" class="site-author-image" rel="start" style="border:none">
              <img class="site-author-image" itemprop="image"
                src="/images/myphoto.jpg"
                alt="长孙雨聪--七星上将" />
			</a>	
            
              <p class="site-author-name" itemprop="name">长孙雨聪--七星上将</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/zhangsunyucong?tab=repositories" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:969887864@qq.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.wanandroid.com/" title="鸿洋_" target="_blank">鸿洋_</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://luodw.cc/" title="罗道文" target="_blank">罗道文</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://litten.me/" title="Litten" target="_blank">Litten</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://luuman.github.io" title="luuman" target="_blank">luuman</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.barretlee.com" title="小胡子哥" target="_blank">小胡子哥</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.halyul.cc" title="halyul" target="_blank">halyul</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/mine_song/article/details/64121769" title="剑指" target="_blank">剑指</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.ithmz.com/" title="奶爸大哥" target="_blank">奶爸大哥</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ruanyifeng.com" title="阮一峰" target="_blank">阮一峰</a>
                  </li>
                
              </ul>
			   
			   <div id="days"></div>
</script>
<script language="javascript">
function show_date_time(){
	window.setTimeout("show_date_time()", 1000);
	BirthDay = new Date("11/24/2017 15:00:00");
	today  =new Date();
	timeold = (today.getTime()-BirthDay.getTime());
	sectimeold = timeold/1000
	secondsold = Math.floor(sectimeold);
	msPerDay = 24*60*60*1000
	e_daysold = timeold/msPerDay
	daysold = Math.floor(e_daysold);
	e_hrsold = (e_daysold-daysold)*24;
	hrsold = setzero(Math.floor(e_hrsold));
	e_minsold = (e_hrsold-hrsold)*60;
	minsold = setzero(Math.floor((e_hrsold-hrsold)*60));
	seconds = setzero(Math.floor((e_minsold-minsold)*60));
	document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
	if (i<10)
	{
		i="0" + i
	};
	return i;
}
show_date_time();
</script>

			  
            </div>
          

         
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Path和Canvas"><span class="nav-number">2.</span> <span class="nav-text">Path和Canvas</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#画点"><span class="nav-number">2.1.</span> <span class="nav-text">画点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#画线"><span class="nav-number">2.2.</span> <span class="nav-text">画线</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#画矩形"><span class="nav-number">2.3.</span> <span class="nav-text">画矩形</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#圆角矩形"><span class="nav-number">2.4.</span> <span class="nav-text">圆角矩形</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#画圆"><span class="nav-number">2.5.</span> <span class="nav-text">画圆</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#画椭圆"><span class="nav-number">2.6.</span> <span class="nav-text">画椭圆</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#画弧"><span class="nav-number">2.7.</span> <span class="nav-text">画弧</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Path"><span class="nav-number">3.</span> <span class="nav-text">Path</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#moveTo"><span class="nav-number">3.1.</span> <span class="nav-text">moveTo</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#lineTo"><span class="nav-number">3.2.</span> <span class="nav-text">lineTo</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#quadTo"><span class="nav-number">3.3.</span> <span class="nav-text">quadTo</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#cubicTo"><span class="nav-number">3.4.</span> <span class="nav-text">cubicTo</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#arcTo"><span class="nav-number">3.5.</span> <span class="nav-text">arcTo</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Path的addArc、addRoundRect、addOval、addRect、addCircle"><span class="nav-number">4.</span> <span class="nav-text">Path的addArc、addRoundRect、addOval、addRect、addCircle</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Path-Op"><span class="nav-number">5.</span> <span class="nav-text">Path.Op</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Path-Op-DIFFERENCE"><span class="nav-number">5.1.</span> <span class="nav-text">Path.Op.DIFFERENCE</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Path-Op-INTERSECT"><span class="nav-number">5.2.</span> <span class="nav-text">Path.Op.INTERSECT</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Path-Op-REVERSE-DIFFERENCE"><span class="nav-number">5.3.</span> <span class="nav-text">Path.Op.REVERSE_DIFFERENCE</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Path-Op-XOR"><span class="nav-number">5.4.</span> <span class="nav-text">Path.Op.XOR</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最后，例子"><span class="nav-number">6.</span> <span class="nav-text">最后，例子</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">长孙雨聪--七星上将</span>
  
</div>

Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  







  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/canvas_lines.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytlJYAPJ';
      var conf = '72c4d5b62ad9725c5f533c23a6f1097e';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2YPqqc43cMkbPegNE3Auieo4-gzGzoHsz", "TVVsPYw3swS3SrByLqNtqlAL");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>


  
</body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
